package app.itgungnir.compose.wan.business.register

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import app.itgungnir.compose.wan.widgets.WanScaffold
import com.google.accompanist.insets.navigationBarsPadding

@Composable
fun RegisterScreen(navController: NavController = rememberNavController()) {
    val viewModel = viewModel<RegisterViewModel>()
    // UI
    WanScaffold(
        modifier = Modifier.navigationBarsPadding(),
        title = "用户注册",
        navController = navController,
        loadingState = viewModel.loadingState.collectAsState(),
        loadingJob = viewModel.loadingJob,
        errorState = viewModel.errorState.collectAsState(initial = null)
    ) {
        RegisterUI(navController = navController) { userName, password, confirmPassword ->
            viewModel.register(userName, password, confirmPassword)
        }
    }
    // State observations
    RegisterSuccessObservation(viewModel = viewModel, navController = navController)
}

@Composable
private fun RegisterSuccessObservation(
    viewModel: RegisterViewModel = viewModel(),
    navController: NavController = rememberNavController()
) {
    val registerSuccessState by viewModel.registerSuccessState.collectAsState(initial = false)
    LaunchedEffect(key1 = registerSuccessState) {
        if (registerSuccessState) {
            navController.previousBackStackEntry?.savedStateHandle?.set("user_has_login", true)
            navController.popBackStack()
        }
    }
}
